// pages/myback/myback.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageRoot: app.globalData.imageRoot,
    myl: false,
    ani: null,
    num: 1,
    check: 0,
    active: 0,
    list: [],
    status: ["不限","待服务", "服务中", "待评价", "已完成"],
    option1: [{
        text: '默认排序',
        value: 0
      },
      {
        text: '价格最高',
        value: 1
      },
      {
        text: '价格最低',
        value: 2
      },
      {
        text: '最新发布',
        value: 3
      },
      {
        text: '折扣率最低',
        value: 4
      },
    ],
    value1: 0,
    value2: 'a',
    state: {
      province: false,
      city: false,
      area: false
    },
    val: {
      province: null
    },
    actProvince: ['北京市'],
    actCity: ['北京市', '北京市'],
    actArea: [110000, 110100, 110101],
    page_token: 0
  },
  areaReset(e){
    let that = this;
    that.setData({page_token:0 })
    var data = {
      page_size:10,
      page_token:0
    }
    that.api(data)
    that.selectComponent('#item2').toggle();
  },
  timeReset(){
    this.setData({
      page_token:0
    })
    var data = {
      page_token:0,
      page_size:10
    }
    this.api(data)
    this.selectComponent('#item3').toggle();
  },
  preventdefault:function(){},
  onReachBottom() { //上拉加载更多
    var that = this;
    //检查是否还有数据可以加载
    var total_size = that.data.list.total_size;
    var size = that.data.list.results.length;
    var page_token = that.data.page_token
    //如果还有，则继续加载
    if (total_size > size) {
      var data = {
        page_size: 10,
        ordertype: that.data.active,
        page_token: page_token += 1,
      }
      that.api(data)
      //如果没有了，则停止加载，显示没有更多内容了
    } else {
      that.setData({
        myl: true
      })
    }
    that.setData({
      page_token: page_token
    })
  },
  search(e) { //搜索
    var ordertype = this.data.active;
    var data = {
      title:e.detail,
      ordertype: ordertype,
      page_size: 10,
      page_token: 0
    };
    this.api(data)
  },
  onChange(event) {
    var that = this;
    var index = event.detail.index;
    that.setData({
      active: index,
      page_token:0,
      myl:false
    })
    var data = {
      ordertype: index,
      page_size: 10,
      page_token: 0
    }
    that.api(data)
  },
  itemClick: function (e) {
    this.setData({
      num: e.currentTarget.dataset.num
    })
  },
  routerOrder() {
    wx.navigateTo({
      url: '../bookingorder/bookingorder',
    })
  },
  check(e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    var check = e.currentTarget.dataset.index;
    that.setData({
      check: check
    })
  },
  stage(e) { //阶段筛选
    var that = this;
    var ordertype = that.data.active;
    var data = {
      ordertype: ordertype,
      page_size: 10,
      page_token: 0
    };
    that.setData({
      page_token:0
    })
    that.api(data);
    that.selectComponent('#item1').toggle();
  },
  inEnter(e) {
    var that = this;
    var ordertype = that.data.active;
    var district = (e.detail.area.value=='全市'?'':e.detail.area.value);
    var city = (e.detail.city.value=='全省'?'':e.detail.city.value);
    var province = (e.detail.province.value=='全国'?'':e.detail.province.value);
    var data = {
      ordertype: ordertype,
      province: province,
      city: city,
      district: district,
      page_size:10,
      page_token:0
    }
    that.api(data);
    that.selectComponent('#item2').toggle();
  },
  userInfo(user) {
    var that = this;
    var list = that.data.list;
    let liky = user.results.filter((p) => {
      return p.client
    })
    let v = [];
    for (let i = 0; i < liky.length; i++) {
      v[i] = liky[i].client
    }
    getApp().ports.api27({
      data: v
    }).then((res) => {
      var res = res.data;
      for (let i in user.results) {
        for (let j in res) {
          if (user.results[i].client == res[j].id) {
            user.results[i].markName = res[j].nickname;
            user.results[i].avatar_url = res[j].avatar_url;
            user.results[i].telphone = res[j].phone;
          }
        }
      }
      that.setData({
        list: user
      })
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      active_color:app.globalData.active_color
    }) 
    var data = {
      page_size: 10,
      page_token: 0
    }
    this.api(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // var animation = wx.createAnimation({
    //   duration: 4000,
    //   timingFunction: 'ease',
    //   delay: 0,
    //   transformOrigin:"50% 50%"
    //  });
    //  animation.translateX(200).opacity(1).step()
    //  this.setData({
    //   ani: animation.export()
    //  })
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // var data = {}
    // this.api(data)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page_token:0
    })
    this.api({ ordertype: this.data.active,});
    setTimeout(()=>{
      wx.stopPullDownRefresh()
    },1000)
  },
  areaInEnter(e) {
    var that = this;
    var ordertype = that.data.active;
    var reg = /[\u4e00-\u9fa5]/g;
    var time = e.detail.years + '-' + e.detail.months + '-' + e.detail.days;
    var createTime = time.replace(reg, "")
    var data = {
      ordertype: ordertype,
      createTime: createTime,
      page_size: 10,
      page_token: 0
    }
    that.api(data)
    that.selectComponent('#item3').toggle();
  },
  api(data) {
    var that = this;
    // if(that.data.check == 0 || that.data.check == 1) {
    //   data.stage = 0
    // }else{
    //   data.stage = that.data.check
    // };
    data.stage = that.data.check
    wx.showLoading({
      title: '加载中',
    })
    getApp().ports.api18({
      data: data
    }).then((res) => {
      var res = res.data;
      if (data.page_token >= 1) {
        res.results.forEach(item => {
          item.time = app.timeFormat(item.createTime, true)
          switch (item.type) {
            case 2:
              item.banner = that.data.imageRoot + item.banner;
              break;
            case 3:
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'
              item.title = item.clientName+' '+item.title +' ' + item.builtUpAreaSquareCentimeter+'㎡'+' '+item.intentionPriceYuan +'万'
              break;
            case 5:
              let total_budget_price_yuan = ['200万以下','200-500万','500-100万','1000万以上'];
              let house_area = ['50㎡以下','50㎡-90㎡','90㎡-144㎡',,'144㎡以上'];
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/hf.png'
              item.title = item.clientName+' ' + item.province + item.district + ' ' + total_budget_price_yuan[item.totalBudgetPriceYuan] + ' ' + house_area[item.houseArea]
              break;
            case 6:
              let order_types = ['', '个人转贷','企业转贷'];
              let budget_price_yuan = ['50万以下','50万-150万','150万-300万','300万以上'];
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/zz.jpg'
              item.title =  item.clientName+' ' + order_types[item.orderType] + ' ' + budget_price_yuan[item.budgetPriceYuan]
              break;
          }
          if (item.type != 3 && item.type != 5 && item.type != 6) {
            item.url = '../fpReserve/fpReserve?id=' + item.id + '&type=' + item.type
          } else {
            item.url = '../fpyy/fpyy?id=' + item.id + '&type=' + item.type
          }
        item.active = 0
        that.data.list.results.push(item)
        })
        res.results = that.data.list.results
      }else{
        res.results.forEach(item => {
          item.active = 0
          item.time = app.timeFormat(item.createTime, true)
          switch (item.type) {
            case 2:
              item.banner = that.data.imageRoot + item.banner;
              break;
            case 3:
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'
              item.title = item.clientName+' '+item.title +' ' + item.builtUpAreaSquareCentimeter+'㎡'+' '+item.intentionPriceYuan +'万'
              break;
            case 5:
              let total_budget_price_yuan = ['200万以下','200-500万','500-100万','1000万以上'];
              let house_area = ['50㎡以下','50㎡-90㎡','90㎡-144㎡',,'144㎡以上'];
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/hf.png'
              item.title = item.clientName+' ' + item.province + item.district + ' ' + total_budget_price_yuan[item.totalBudgetPriceYuan] + ' ' + house_area[item.houseArea]
              break;
            case 6:
              let order_types = ['', '个人转贷','企业转贷'];
              let budget_price_yuan = ['50万以下','50万-150万','150万-300万','300万以上'];
              item.banner = 'https://api.yipaiju.com/resources/images/wawa/zz.jpg'
              item.title =  item.clientName+' ' + order_types[item.orderType] + ' ' + budget_price_yuan[item.budgetPriceYuan]
              break;
          }
          if (item.type != 3 && item.type != 5 && item.type != 6) {
            item.url = '../fpReserve/fpReserve?id=' + item.id + '&type=' + item.type
          } else {
            item.url = '../fpyy/fpyy?id=' + item.id + '&type=' + item.type
          }
        })
      }
      that.setData({
        list: res,
      })
      wx.hideLoading({
        success: (res) => {},
      })
      // that.userInfo(res)
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  sort(e) { //排序
    var that = this;
    var active = that.data.active;
    var value = e.detail;
    var list = that.data.list;
    var data = {
      ordertype: that.data.active,
      page_size: 10,
      page_token: 0
    }
    switch (value) {
      case 0:
        that.api(data)
        break;
      case 1:
        list.results = list.results.sort(that.sortBy('price_yuan', false))
        break;
      case 2:
        list.results = list.results.sort(that.sortBy('price_yuan'));
        break;
      case 3:
        list.results = app.ReverseRankingDate(list.results, "time");
        break;
      case 4:
        list.results = list.results.sort(that.sortBy('discount_rate', true))
        break;
    }
    that.setData({
      list: list
    })
  },
  dateData(property, bol) { //最新排序
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      if (bol) {
        // 升序
        return Date.parse(value1) - Date.parse(value2);
      } else {
        // 降序
        return Date.parse(value2) - Date.parse(value1)
      }

    }
  },
  sortBy(attr, rev) { //价格排序
    //第二个参数没有传递 默认升序排列
    if (rev == undefined) {
      rev = 1;
    } else {
      rev = (rev) ? 1 : -1;
    }

    return function (a, b) {
      a = a[attr];
      b = b[attr];
      if (a < b) {
        return rev * -1;
      }
      if (a > b) {
        return rev * 1;
      }
      return 0;
    }
  },
})